# -*- coding: utf-8 -*-
#
# Collector, the Audio CD collection manager
# Copyright (C) 2006 Piotr Gaczkowski
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

import musicbrainz2.disc as mbdisc
import musicbrainz2.webservice as mbws
import re
from col.debug import debug

class disc:
  def __init__(self, id, cddb_id = None):
    """
    Constructs a disc object, where id is the MusicBrainz discID and optional
    cddb_id is the CDDB discID used for fallback
    """

    self.id = id
    self.cddb_id = cddb_id
    self.info = []

  def getInfo(self, query, fallback = None, debug = None):
    """
    Retrieves disc info from MusicBrainz using discID. If it fails
    method optionally queries MusicBrainz, using CDDB data.
    """

    filter = mbws.ReleaseFilter(discId = self.id)
    results = query.getReleases(filter=filter)

    if len(results) != 0:
      inc = mbws.ReleaseIncludes(artist=True, tracks=True, releaseEvents=True, urlRelations=True)
      for result in results:
        release = query.getReleaseById(result.release.getId(), inc)
        self.info.append(self.rel2info(release))

    else:
      if fallback and self.cddb_id:
          import CDDB

          debug("Warning: using FreeDB fallback method!\n")
          self.cddb_info = []
          (query_stat, query_info) = CDDB.query(self.cddb_id)

          if query_stat == 200:
            # Successful query

            self.cddb_info.append(re.split(' */ *', query_info['title']))

          elif query_stat == 210 or query_stat == 211:
            # Multiple matches

            for i in query_info:
              self.cddb_info.append(re.split(' */ *', i['title']))

          else:
            # Failed to get disc info from CDDB

            raise CDDBQueryError

          for i in self.cddb_info:
            filter = mbws.ReleaseFilter(title = i[1], artistName = i[0])
            results = query.getReleases(filter)

            if len(results) != 0:
              inc = mbws.ReleaseIncludes(artist=True, tracks=True, releaseEvents=True, urlRelations=True)
              for result in results:
                release = query.getReleaseById(result.release.getId(), inc)
                self.info.append(self.rel2info(release))
            else:
              debug("No results :(\n")

    if debug:
      print self.info

  def uglyPrint(self):
    print self.info

  def prettyPrint(self):
    for i in self.info:
      print "Disc ID: %s %s.html" % (self.id, i['id'])
      print "Artist name: %s; sortName: %s" % (i['artist']['name'], i['artist']['sortName'])
      print "ASIN: %s" % i['asin']
      for r in i['releaseEvents']:
        print "%s, %s" % (r['date'], r['country'])
      print "Title: %s" % i['title']
      for t in i['tracks']:
        dur = "%s:%02d" % (t['duration'] / 60000, (t['duration'] % 60000) / 1000)
        if t['artist'] is not None:
          print "%s - %s (%s)" % (t['artist']['name'], t['title'], dur)
        else:
          print "%s (%s)" % (t['title'], dur)
      for t in i['types']:
        print t;

  def rel2info(self, release):
    relInfo = dict()
    relInfo['id'] = release.id
    relInfo['artist'] = dict()
    relInfo['artist']['name'] = release.getArtist().getUniqueName()
    relInfo['artist']['sortName'] = release.getArtist().getSortName()
    relInfo['artist']['id'] = release.getArtist().id
    relInfo['asin'] = release.getAsin()
    relInfo['releaseEvents'] = []
    rev = dict()
    for ev in release.getReleaseEvents():
      rev['country'] = ev.getCountry()
      rev['date'] = ev.getDate()
      relInfo['releaseEvents'].append(rev)
    relInfo['title'] = release.getTitle()
    relInfo['tracks'] = []
    tr = dict()
    for t in release.getTracks():
      if t.getArtist() is not None:
        tr['artist'] = dict()
        tr['artist']['name'] = t.getArtist().getName()
        tr['artist']['id'] = t.getArtist().id
      else:
        tr['artist'] = None
      tr['title'] = t.getTitle()
      tr['duration'] = t.getDuration()
      relInfo['tracks'].append(tr.copy())
    relInfo['types'] = release.getTypes()
    relInfo['single'] = release.isSingleArtistRelease()

    return relInfo

class disc_pack:
  def __init__(self):
    self.service = mbws.WebService()
    self.query = mbws.Query(self.service)
    self.discs = []
    self.needs_update = False

  def add(self, id, cddb_id = None):
    self.discs.append(disc(id, cddb_id))
    self.needs_update = True

  def getData(self, fallback = None, debug = None):
    self.needs_update = False
    for d in self.discs:
      if d.info == []:
        d.getInfo(self.query, fallback, debug)

  def len(self):
    return len(self.discs)

  def prettyPrint(self):
    for d in self.discs:
      d.prettyPrint()

  def uglyPrint(self):
    for d in self.discs:
      d.uglyPrint()

  def updatable(self):
    return self.needs_update
